﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System;

namespace block_explorer
{
    class DirectionalLightRenderer
    {
        private Effect mLightEffect;

        public DirectionalLightRenderer()
        {
        }

        public void Prepare(GraphicsDevice device, ContentManager content)
        {
            mLightEffect = content.Load<Effect>("Effects/DirectionalLight");
        }

        public void RenderLight(DirectionalLight light, Camera camera, DeferredRenderer renderer)
        {
            mLightEffect.CurrentTechnique = mLightEffect.Techniques["Light"];
            mLightEffect.Parameters["View"].SetValue(camera.View);
            mLightEffect.Parameters["InverseView"].SetValue(Matrix.Invert(camera.View));
            mLightEffect.Parameters["InverseProjection"].SetValue(Matrix.Invert(camera.Projection));

            if (light.Shadows)
            {
                mLightEffect.Parameters["LightView"].SetValue(light.Views);
                mLightEffect.Parameters["LightProjection"].SetValue(light.Projections);
                mLightEffect.Parameters["InverseLightProjection"].SetValue(light.InverseProjections);
                mLightEffect.Parameters["CascadeDepths"].SetValue(light.ClipPlanes);
                mLightEffect.Parameters["CascadeWidth"].SetValue(light.CascadeWidth);
            }

            mLightEffect.Parameters["LightDirection"].SetValue(light.Direction);
            mLightEffect.Parameters["LightColor"].SetValue(light.Color.ToVector3());

            mLightEffect.Parameters["HalfPixel"].SetValue(renderer.GBufferHalfPixel);

            mLightEffect.Parameters["Shadows"].SetValue(light.Shadows);

            mLightEffect.Parameters["DepthMap"].SetValue(renderer.GBuffer.Depth);
            mLightEffect.Parameters["NormalMap"].SetValue(renderer.GBuffer.Normal);
            mLightEffect.Parameters["ShadowMap"].SetValue(light.ShadowMap);

            mLightEffect.CurrentTechnique.Passes[0].Apply();
            Util.QuadRenderComponent.Instance.Render(-1 * Vector2.One, Vector2.One);
        }
    }
}
